<!--
 @description 搭配产品编辑（数量，优惠方式，优惠）
 @fileName CollocationEdit.vue
 @author zengqiongying
 @created 2024/08/19 13:07:41
-->
<template>
  <el-dialog
    ref="refDlg"
    v-el-drag-dialog
    width="500px"
    title="搭配产品"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @close="closeDialog"
  >
    <el-form ref="form" :model="formData" :rules="formRules" size="mini" label-width="100px">
      <el-form-item label="数量" prop="qty">
        <el-input v-model.number="formData.qty" placeholder="请输入" maxlength="10" />
        <!-- <el-input-number v-model="num" @change="handleChange" :min="1" :max="10"></el-input-number> -->
      </el-form-item>
      <el-form-item label="优惠方式" prop="discountMethod">
        <el-radio-group v-model="formData.discountMethod" @change="handleTypeChange">
          <el-radio :label="0">无</el-radio>
          <el-radio :label="1">折扣</el-radio>
          <el-radio :label="2">立减</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if=" [1, '1', 2, '2'].includes(formData.discountMethod)"
        label="优惠"
        prop="discount"
        :rules=" [
          { required: [1, '1', 2, '2'].includes(formData.discountMethod), message: '请输入', trigger: 'blur' },
          { validator: validateDiscount, trigger: 'blur' }
        ]"
      >
        <el-input v-model="formData.discount" placeholder="请输入" maxlength="10">
          <template slot="append">{{ [2,'2'].includes(formData.discountMethod)?'元':'折' }}</template>
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button type="primary" size="mini" @click="handleSure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveQtyAndDiscount } from '@/api/productCombine/detail'
export default {
  name: 'CollocationEdit',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    const validateDiscount = (rule, value, callback) => {
      if (!value && [1, '1', 2, '2'].includes(this.formData.discountMethod)) {
        return callback(new Error('优惠不能为空'))
      }
      if ([2, '2'].includes(this.formData.discountMethod)) {
        const isAmount = /^\d+(\.\d{1,2})?$/.test(value)
        if (!isAmount) {
          return callback(new Error('请输入有效的金额，最多两位小数'))
        }
      }
      if ([1, '1'].includes(this.formData.discountMethod)) {
        const isAmount = /^\d+(\.\d{1,2})?$/.test(value)
        if (!isAmount || (Number(value) <= 0 || Number(value) >= 10)) {
          return callback(new Error('请输入有效的折扣，最多两位小数'))
        }
        if ((Number(value) <= 0 || Number(value) >= 10)) {
          return callback(new Error('请输入有效的折扣，不能大于10'))
        }
      }
      callback()
    }
    return {
      formData: {
        qty: 1,
        discountMethod: 0,
        discount: ''
      },
      formRules: {
        qty: [
          { required: true, message: '请输入', trigger: 'blur' },
          { type: 'number', message: '数量必须为整数' }
        ],
        discountMethod: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },
      validateDiscount,
      submiting: false
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },

  created() {
    if (this.detail && this.detail.id) {
      Object.keys(this.formData).forEach(k => {
        const val = this.detail[k] || ''
        this.$set(this.formData, k, k === 'discountMethod' ? Number(val || 0) : val)
      })
    }
  },
  methods: {
    closeDialog() {
      for (const k in this.formData) {
        this.$set(this.formData, k, '')
      }
      this.dialogShow = false
    },
    handleTypeChange() {
      if ([1, '1', 2, '2'].includes(this.formData.discountMethod)) {
        this.$refs.form.validateField('discount')
        return
      }
      this.$set(this.formData, 'discount', '')
    },
    // 提交表单处理
    handleSure() {
      if (this.submiting) return
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          const data = {
            ...this.formData,
            ...{
              id: this.detail.id
            }
          }
          this.submiting = true
          saveQtyAndDiscount(data).then(res => {
            this.submiting = false
            this.$emit('success')
            this.closeDialog()
          }).catch(() => {
            this.submiting = false
          })
        }
      })
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
